import $ from 'jquery';
import Vue from 'vue';
import { each, template, partialRight } from 'lodash';
import preview from './image-preview';

function init() {
  let $form = $('#product-new');
  const time = new Date();
  let publishDate = new Vue({
    el: '#publish-date',
    data: {
      year: time.getFullYear(),
      month: 1,
      date: null
    },
    methods: {
      update: function () {
        let month = this.month > 9 ? this.month : `0${this.month}`;
        this.date = `${this.year}-${month}-01`;
      }
    },
    ready: function() {
      this.update();
    }
  });

  const RecomendedPlatform = new Vue({
      el: '#recommended-platform',
      data: {
        newPlatform: '',
        platformList: [],
      },
      methods: {
        addPlatform: function() {
          const text = this.newPlatform.trim();
          if (text) {
            this.platformList.push(text)
            this.newPlatform = '';
          }
        },
        removePlatform: function(index) {
          this.platformList.splice(index, 1);
        }
      }
  })

  let logoUploadPreview = preview({
    limit: 1,
    template: '#logo-upload .template',
    previewArea: '#logo-upload #preview',
    previewClass: 'image-preview',
    addButtonClass: 'image-upload-icon'
  });

  let productScreentshots = preview({
    limit: 6,
    template: '#product-upload .template',
    previewArea: '#product-upload #preview',
    previewClass: 'image-preview',
    addButtonClass: 'image-upload-icon'
  });

  $('#submit').on('click', function () {
    ga('send', 'event', 'product', 'click_submit', 'done');
    if(validator().pass) {
      if(confirm('产品信息一旦提交将无法更改，是否确认提交')) {
        submitData();
      }
    } else {
      let message = validator().msg;
      ga('send', 'event', 'product', 'validator_error', message);
      alert(message);
    }
  });

  function submitData() {
    let url = $form.attr('action');
    let method = $form.attr('method');
    let fd = new FormData(document.getElementById('product-new'));
    let $loading = $form.find('.loading');

    $loading.addClass('loading-show');

    $.ajax({
      url,
      data: fd,
      cache: false,
      processData: false,
      // contentType: 'multipart/form-data',
      contentType: false,
      type: method
    }).fail(function (jqXHR) {
      let errors = '';
      _.forEach($.parseJSON(jqXHR.responseText), (n, key) => {
        _.forEach(n, error => errors = errors + error + '');
      });
      ga('send', 'event', 'product', 'ajax_error', errors);
      alert('请检查表单：' + errors);
    }).done(function () {
      ga('send', 'event', 'product', 'ajax_done', 'submit success');
      setTimeout(() => location.href = '/products/success', 300);
    }).always(function () {
      $loading.removeClass('loading-show');
    });
  }

  function validator() {
    if(!maxLength('#product_description')) return { pass: false, msg: '详情描述过长' };
    if(!maxLength('#product_summary')) return { pass: false, msg: '产品描述过长' };
    if(!uploadedImage('#logo-upload')) return { pass: false, msg: '请上传产品LOGO' };
    if(!uploadedImage('#product-upload')) return { pass: false, msg: '请上传产品图片' };
    if(!checkRule('url')) return { pass: false, msg: '产品网址格式不对' };
    if(!checkRule('weibo')) return { pass: false, msg: '微博网址格式不对' };
    if(!checkRule('email')) return { pass: false, msg: '邮箱格式不对' };
    if(!notEmpty()) return { pass: false, msg: '所有表单都是必填项喔'};
    return { pass: true }
  }

  function notEmpty() {
    return $form.find('input[name^=product][type=text],textarea')
      .filter(function () {
        return !$(this).hasClass('validator-not-require');
      }).filter(function () {
        return $(this).val().length === 0;
      }).length === 0;
  }

  function uploadedImage(selector) {
    return $form.find(selector).find('#preview .image-preview').length > 0;
  }

  function maxLength(selector){
    let $dom = $form.find(selector);
    return $dom.val().length < $dom.data('length');
  }

  const ruleReg = {
    email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
    url: /.*([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/i,
    weibo: /.*(weibo.com)([\/\w \.-]*)*\/?/i
  };

  function checkRule(type) {
    return $form.find('input[data-rule*='+type+']').filter(function () {
      var text = $(this).val();
      return text != '' && !ruleReg[type].test(text);
    }).length === 0;
  }
} // fun init end

export default init;
